var toggle_tabs = {};
var tabs = {};

$(document).ready(function(){
	$(window).trigger( 'hashchange' );
	
	$('.slide_menu_left').click(function(){
	    if($(".nav-collapse.collapse").hasClass('open_left')){
	      sidemenu_close();
	    }else{
	      sidemenu_open();
	      $('.main_container').bind('click', function(){
	        sidemenu_close();
	      });
	      var handler = function() {
	  			sidemenu_close();
	  		};
		    $(window).bind('resize', handler);
	    }
	});	
	
	if(typeof(jQuery.validator) != "undefined")
    {
         jQuery.validator.setDefaults({
             showErrors: function (errorMap, errorList) {
                 this.defaultShowErrors();
                 
                 // destroy tooltips on valid elements
                 //fix for chosen
                 if(jQuery("." + this.settings.validClass).next().hasClass("chzn-container-multi"))
                 {
                	 jQuery("." + this.settings.validClass).next().tooltip("destroy");
                	 jQuery("." + this.settings.validClass).next().find("ul.chzn-choices").removeClass("error");
                 }
                 else if(jQuery("." + this.settings.validClass).next().hasClass("chzn-container"))
                 {
                	 jQuery("." + this.settings.validClass).next().tooltip("destroy");
                	 jQuery("." + this.settings.validClass).next().find("a.chzn-single").removeClass("error");
                 }else
                 {
                	 jQuery("." + this.settings.validClass).tooltip("destroy");
                 }
                 
                 // add/update tooltips
                 for (var i = 0; i < errorList.length; i++) {
                     var error = errorList[i];
                     //fix for chosen
                     if($(error.element).next().hasClass("chzn-container-multi"))
                     {
                    	 jQuery($(error.element).next())
                         .tooltip({ trigger: "hover" })
                         .attr("data-original-title", error.message);
                    	 jQuery($(error.element).next()).find("ul.chzn-choices").addClass("error");
                     }else if($(error.element).next().hasClass("chzn-container"))
                     {
                    	 jQuery($(error.element).next())
                         .tooltip({ trigger: "hover" })
                         .attr("data-original-title", error.message);
                    	 jQuery($(error.element).next()).find("a.chzn-single").addClass("error");
                     }else
                     {
                    	 jQuery(error.element)
                         .tooltip({ trigger: "focus" })
                         .attr("data-original-title", error.message)
                     }
                     
                 }
             }
         });
         $.validator.setDefaults({ ignore: '' });
    }
})

// slide menu in
function sidemenu_open(){
      $(".main_container").stop().animate({
          'left': '150px'
      }, 250, 'swing');
      $(".nav-collapse.collapse").stop().animate({
          'left': '0'
      }, 250, 'swing').addClass('open_left');
}

function sidemenu_close(){
    $(".main_container").stop().animate({
        'left': '0'
    }, 250, 'swing');
    $(".nav-collapse.collapse").stop().animate({
        'left': '-150px'
    }, 250, 'swing').removeClass('open_left');
    $('.main_container').unbind('click');
    if(typeof handler != 'undefined'){
      $(window).unbind('resize', handler);
    }
}

function showLoader(element)
{
	//$("#loading_wrapper").show();
	element = element || $('body');
	if(element.find(".modal-scrollable").length > 0) return;
	element.modalmanager('loading');
}

function hideLoader(element)
{
	//$("#loading_wrapper").hide();
	element = element || $('body');
	element.modalmanager('removeLoading');
	$("body").removeClass("modal-open");
}

function getMainContent()
{
	return $("#main_container");
}

function initControl(id)
{
	$("select[data-toggle='chosen']",$(id)).each(function(){
		var search = false;
		if(($(this).attr('search') == 'false'))
		{
			search = true;
		}
		$(this).chosen({
			no_results_text: 'Không tìm thấy:',
			"disable_search": search,
			search_contains: true,
			width: "100%"
		});
	})	
}

function showModalLink(obj)
{
	var link = obj.link;
	var div = $("<div class='modal custom_modal' data-width='760'></div>");
	var html = '<div class="modal-header">';
		html += '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>';
		html += '</div>';
		html += '<div class="modal-body"></div>';
	div.append(html);	
	var modal_body = $(".modal-body",div); 
	$('body').modalmanager('loading');
	
	
	modal_body.load(link, '', function(){
		div.modal();
		div.on("hidden",function(){
			div.remove();
		})
		
		if(typeof(obj.callback) != "undefined" && typeof(obj.callback != null))
		{
			obj.callback();
		}
    });
}

function showModalElement(el)
{
	var div = $("<div class='modal custom_modal'></div>");
	var html = '<div class="modal-header">';
		html += '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>';
		html += '</div>';
		html += '<div class="modal-body"></div>';
	div.append(html);
	var modal_body = $(".modal-body",div); 
	modal_body.append(el);
	div.modal();
	div.on("hidden",function(){
		div.remove();
	})
}

function showModalPermission($section)
{
	var obj = {};
	var link = "index.php?option=com_ketnoi&view=phanquyen&tmpl=raw&section="+$section;
	obj.link = link;
	var callback = function(){
		initCreatePhanquyen();
	}
	obj.callback = callback;
	showModalLink(obj);
}

function AddCellLabel(gridid)
{
	jQuery("#"+gridid+" thead tr th").each(function(){
		var text = jQuery(this).text();
		var index = jQuery(this).index();
		jQuery(this).closest(".k-grid").find("tbody tr").each(function(){
			jQuery(this).find("td:eq("+index+")").attr("data-label",text);
		})
	})
}

function microtime (get_as_float) {
	var now = new Date().getTime() / 1000;
	var s = parseInt(now, 10);

	return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}

function addmorefile(el,container,name)
{
	var timestamp = microtime(true).toString();
 	var split_id = timestamp.split('.');
 	var id = split_id.join("_");
 	var input = $('<input type="file" name="'+name+'[]" id="'+id+'"  onchange="handleFiles(this.files,\''+id+'\',\''+container+'\',true)">');
 	var parent = $(el).parent();
 	input.css("display","none");
 	parent.append(input);
 	input.trigger("click");
}

function addonefile(el,container,name)
{
	var timestamp = microtime(true).toString();
 	var split_id = timestamp.split('.');
 	var id = split_id.join("_");
 	var parent = $(el).parent();
 	if(parent.find("input[type='file']").length <= 0)
 	{
 		var input = $('<input type="file" name="'+name+'[]" id="'+id+'"  onchange="handleFiles(this.files,\''+id+'\',\''+container+'\',false)">');
 	 	input.css("display","none");
 	 	parent.append(input);
 	 	input.trigger("click");
 	}else
 	{
 		parent.find("input[type='file']").trigger("click");
 	}
 	
 	
}

function handleFiles(files,input_id,container,isMore) {
	window.URL = window.URL || window.webkitURL;
	var fileList = document.getElementById(container);
    if (files.length) {
	    for (var i = 0; i < files.length; i++) {
		    var file = files[i];
		    var imageType = /image.*/;
	    	if (!file.type.match(imageType)) {
    	    	continue;
    	    }
	       
	      	var img = document.createElement("img");
	      	img.setAttribute("class","img-polaroid");
	      	img.src = window.URL.createObjectURL(files[i]);
	      	img.height = 60;
	      	img.onload = function(e) {
	        	window.URL.revokeObjectURL(this.src);
	    	}

	      	var img_tmp = document.createElement("img");
	      	img_tmp.style.display = "none";
	      	img_tmp.setAttribute("class","img_tmp");
	      	img_tmp.src = window.URL.createObjectURL(files[i]);
	      	img_tmp.height = 60;
	      	img_tmp.onload = function(e) {
	        	window.URL.revokeObjectURL(this.src);
	    	}

	      	var div = document.createElement("div");
	      	var a = document.createElement("a");
	      	a.setAttribute("file_id",input_id);
	      	var icon = document.createElement("i");
	      	icon.setAttribute("class","icon-remove");
			a.appendChild(icon);
			div.appendChild(img);
			div.appendChild(img_tmp);
			div.appendChild(a);
			if(isMore)
				fileList.appendChild(div);
			else $(fileList).html(div);
	    }
	    
  	}
}

jQuery("#fileList img.img-polaroid").live("click",function(){
	var image = $(this).closest("div").find("img.img_tmp");
	var el = this;
	image.css("display","block");
	var div = $("<div class='modal custom_modal'></div>");
	var html = '<div class="modal-header">';
		html += '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>';
		html += '</div>';
		html += '<div class="modal-body"></div>';
	div.append(html);
	var modal_body = $(".modal-body",div); 
	modal_body.append(image);
	div.modal();
	div.on("hidden",function(){
		var image_back = modal_body.find("img.img_tmp");
		image_back.css("display","none");
		$(el).closest("div").append(image_back);
		div.remove();
	})
})

jQuery("#fileList a").live("click",function(){
	var id = $(this).attr("file_id");
	var img_name = $(this).attr("img_name");
	
	$("#"+id).remove();
	if(typeof(img_name) != "undefined")
	{
		var data = JSON.parse($("#delete_file").val());
		data.push(img_name);
		$("#delete_file").val(JSON.stringify(data));
	}
	$(this).parent().remove();
})


function checkJSON(data)
{
	var obj = {};
	var IS_JSON = true;
	var result = "";
	
	try
	{
		result = jQuery.parseJSON(data);
	}
	catch(err)
	{
		IS_JSON = false;
	} 
	obj.is_json = IS_JSON;
	obj.result = result;
	return obj;
}

function number_format (number, decimals, dec_point, thousands_sep) {	  
  number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
      var k = Math.pow(10, prec);
      return '' + Math.round(n * k) / k;
    };
  // Fix for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || '';
    s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dec);
}

jQuery.fn.input_number = function(){
	//catch input: number -> valid , character -> invalid
	var reg = /^[0-9]*$/;
	var update_string = jQuery(this).val();
	
	if(!reg.test(update_string))
	{
		jQuery(this).val("");
		update_string = "";
	}
	
	jQuery(this).bind('keypress',function(event){
		var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;

		if(key == 8 || key == 46 || key == 13)
		{
			return true;
		}
		var string = jQuery(this).val() + String.fromCharCode(key);
		
		if(reg.test(string))
		{	
			update_string = string;
			return true;
		}
			
		return false;
	});
	
	jQuery(this).bind('keyup',function(event){
		var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
		if(key == 8 || key == 46 || key == 13 || key == 37 || key == 39)
		{
			return true;
		}
		if(jQuery.trim(jQuery(this).val()) != "")
			jQuery(this).val(parseInt(jQuery(this).val()));	
	});
	
	jQuery(this).bind('blur',function(event){
		if(jQuery.trim(jQuery(this).val()) != "")
			jQuery(this).val(parseInt(jQuery(this).val()));
	});
	
	var ctrlDown = false;
	var ctrlKey = 17, vKey = 86, cKey = 67;
	jQuery(document).keydown(function(e)
    {
        if (e.keyCode == ctrlKey) ctrlDown = true;
    }).keyup(function(e)
    {
        if (e.keyCode == ctrlKey) ctrlDown = false;
    });
	
	
	jQuery(this).bind('keydown',function(event){
		var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
		//if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey))
		var el = this;
		if(key == 8 || key == 46)
		{
			window.setTimeout(function(){
				var string = jQuery(el).val();
				update_string = string;
			},1)
			return true;
		}
		if (ctrlDown && key == vKey )
		{
			
			window.setTimeout(function(){
				var string = jQuery(el).val();
				if(!reg.test(string))
				{
					jQuery(el).val(update_string);
				}else
				{
					update_string = string;
				}
			},1)
		}
	});
}

